import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    nickname: null as any,
    user: null as any,
    token: '',
    id:''
  }),
  actions: {
    setUser(user: any) {
      this.user = user
      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify(user))
    },
    setToken(token: string) {
      this.token = token
      // 保存到本地存储
      localStorage.setItem('token', token)
    },
    setId(id: number) {
      if (!this.user) {
        this.user = { id };
      } else {
        this.user.id = id;
      }
      localStorage.setItem('user', JSON.stringify(this.user));
    },
    setNickname(nickname: string) {
      this.nickname = nickname
      // 保存到本地存储
      localStorage.setItem('nickname', nickname)
    },
    logout() {
      this.user = null
      this.token = ''
      // 清除本地存储
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      localStorage.removeItem('nickname')
    },
    // clear方法作为logout的别名
    clear() {
      this.logout()
    },
    // 初始化时从本地存储读取数据
    initFromStorage() {
      const storedUser = localStorage.getItem('user')
      const storedToken = localStorage.getItem('token')
      const storedNickname = localStorage.getItem('nickname')

      if (storedUser) {
        this.user = JSON.parse(storedUser)
      }
      if (storedToken) {
        this.token = storedToken
      }
      if (storedNickname) {
        this.nickname = storedNickname
      }
    }
  }
})
